package org.tuestudent.grouppa;

import java.util.ArrayList;
import java.util.Date;

import org.tuestudent.grouppa.WallViewController.AddCommentResponse;
import org.tuestudent.grouppa.WallViewController.GetAllCommentsResponse;

import android.app.AlertDialog;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class ViewTopic extends Fragment implements OnClickListener {

    // GrouppaScreen
    GrouppaScreen grouppaScreen;
    
    public final int topicId;
    private final ForumTopic topic;
    
    private ViewTopic()
    {
        super();
        this.topicId = 0;
        this.topic =  null;
    }
    public ViewTopic(int topicId,ForumTopic topic)
    {
        super();
        this.topicId = topicId;
        this.topic =  topic;
    }
    private ListView commentList;
    private Button postButton;
    private TextView titleView;
    private TextView authorView;
    private TextView dateView;
    private RelativeLayout mainContainer;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        // Inflate the view to its container
        View topicView =
                inflater.inflate(R.layout.fragment_view_post, container, false);

        lastDate=null;
        commentList = (ListView) topicView.findViewById(R.id.ViewPostList);
        postButton = (Button)topicView.findViewById(R.id.buttonPostComment);
        titleView = (TextView)topicView.findViewById(R.id.viewPostTitle);
        authorView = (TextView)topicView.findViewById(R.id.viewPostAuthor);
        dateView = (TextView)topicView.findViewById(R.id.viewPostDateModification);
        mainContainer = (RelativeLayout)topicView.findViewById(R.id.containerViewPost);
        postButton.setOnClickListener(this);
        grouppaScreen = Main.getContext().grouppaActivity;
        commentListAdapter = new ArrayAdapter<String>(getActivity(), R.layout.comments_list_item,visibleComments);
        commentList.setAdapter(commentListAdapter);
        
        // Change the title in the actionbar
        if ( !topic.title.equals(null))
            getActivity().getActionBar().setTitle(topic.title);
        
        return topicView;
    }
    
    private void createCommentPopup() {
        
      //make the popup visible
        final AlertDialog createCommentPopup = grouppaScreen.showPopUp(R.layout.popup_post_comment);
        //add a listener to the button of the popup so it can do something when pressed on
        final Button createComment = (Button)createCommentPopup.findViewById(R.id.create_comment);
        
        createComment.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                String comment = ((EditText) createCommentPopup.findViewById(R.id.post_content)).getText().toString();
                
                // Adding an empty comment
                if (!comment.trim().isEmpty())
                {
                    ForumComment newComment = new ForumComment();
                    newComment.author = Main.getContext().currentUserName;
                    newComment.date = new Date();
                    newComment.text = comment;
                    WallViewController.getInstance().addComment(topicId, newComment);
                    createCommentPopup.dismiss();
                } else {
                    // SetError for invalid comment (empty EditText)
                    ((EditText) createCommentPopup.findViewById(R.id.post_content))
                        .setError("Enter your comment...");
                }                     
            }
        });
        
        ImageButton cancel = (ImageButton) createCommentPopup.findViewById(R.id.cancelButton);
        cancel.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                createCommentPopup.dismiss();
            }
        });   
    }

    @Override
    public void onStart() {
        super.onStart();
        Main.getContext().currentGrouppaFragment = this;
        AppContext ctx = Main.getContext();
        ctx.currentGrouppaFragment = this;
        WallViewController wvc = WallViewController.getInstance();
        ctx.setCurrentViewController(wvc);
        wvc.getAllComments(topicId);
    }

    /**
     * response from server after request to add a comment
     * 
     * @param response
     */
    public void onAddCommentResponse(AddCommentResponse response) {
        if(response.topicId != topicId)
            return;
        if(!response.succeeded)
        {
            Main.getContext().grouppaActivity.errorPopup("adding comment failed: "+response.errorReason);
        }
        else
        {
            Main.getContext().grouppaActivity.actionSuccess("comment added!\n It will show up in few seconds.");
        }
    }

    /**
     * Response from server after request to get all comments
     * 
     * @param response
     */
    public void onGetAllCommentsResponse(GetAllCommentsResponse response) {
        if(response.topicId != topicId)
            return;
        lastDate = null;
        titleView.setText("Title: "+topic.title);
        authorView.setText("Author: "+topic.author);
        commentListAdapter.clear();
        commentListAdapter.add(topic.text+"\n\n");
        for(ForumComment comment :  response.comments)
        {
            addCommentToList(comment);
        }
        commentListAdapter.notifyDataSetChanged();
        setLastPostedDate();
        mainContainer.requestLayout();
    }
    private ArrayAdapter<String> commentListAdapter;
    private ArrayList<String> visibleComments = new ArrayList<String>();
    private Date lastDate = null;
    private void setLastDate(Date date)
    {
        if(lastDate == null)
            lastDate = date;
        else
        {
            if(date.compareTo(lastDate)>0)
                lastDate = date;
        }
    }
    
    private void setLastPostedDate()
    {
        Date date = lastDate;
        if(date == null)
            date = topic.date;
        dateView.setText("Last modified: "+Main.getContext().dateFormat.format(date));
    }
    
    private void addCommentToList(ForumComment comment)
    {
        commentListAdapter.add("Author: "+comment.author+ " Date: "+Main.getContext().dateFormat.format(comment.date)+"\r\n"+comment.text);
        setLastDate(comment.date);
    }
    
    /**
     * post button click event
     */
    @Override
    public void onClick(View arg0) {
    	createCommentPopup();
    }
    
    public void onGetNewCommentsResponse(GetAllCommentsResponse response) {
        if(response.topicId != topicId)
            return;
        
        for(ForumComment comment :  response.comments)
        {
            addCommentToList(comment);
        }
        commentListAdapter.notifyDataSetChanged();
        commentList.requestLayout();
        setLastPostedDate();       
    }
}
